/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.R;
import io.renren.common.utils.ResponseModel;
import io.renren.modules.sys.entity.SysConfigEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.form.SysLoginForm;
import io.renren.modules.sys.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@Api(tags = "后台管理登录")
public class SysLoginController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private SysCaptchaService sysCaptchaService;
	@Autowired
	private SysConfigService sysConfigService;

	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	@ApiOperation("验证码")
	public void captcha(HttpServletResponse response, String uuid)throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	@ApiOperation("登录")
	public Map<String, Object> login(@RequestBody SysLoginForm form)throws IOException {
		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		if(!captcha) {
			return R.error("验证码不正确");
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		Date now = new Date();
		Date expiresTime = user.getExpiresTime();
		if(expiresTime != null) {
			 if(expiresTime.before(now)) {
			 	// 过期了
				 return R.error("您的账号已到期，请联系管理员！");
			 }
		}

		user.setIsLogin("1");
		sysUserService.updateById(user);


		// 历史记录+1
		sysConfigService.addNum();

		//生成token，并保存到数据库
		R r = sysUserTokenService.createToken(user.getUserId());

		return r;
	}


	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	@ApiOperation("登出")
	public R logout() {
		SysUserEntity user = super.getUser();
		user.setIsLogin("0");
		sysUserService.updateById(user);
		sysUserTokenService.logout(getUserId());
		return R.ok();
	}

	@GetMapping("/sys/onlineNum")
	@ApiOperation("在线用户数量")
	public ResponseModel<Integer> onlineNum() {
		int number = sysUserService.onlineNum();
		return ResponseModel.of(number);
	}

	@GetMapping("/sys/historyUser")
	@ApiOperation("历史访问用户")
	public ResponseModel<Integer> historyUser() {

		SysConfigEntity configEntity = sysConfigService.getOne(new QueryWrapper<SysConfigEntity>().eq("param_key", "ONLINE"));
		int num = 0;
		if(configEntity != null) {
			num = configEntity.getNum();
		}
		return ResponseModel.of(num);
	}
}
